package com.mysteel.monitor.core.utils;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import sun.tools.attach.HotSpotVirtualMachine;

import java.io.InputStream;
import java.util.List;

public class MapUtil {

    public static List<String> excute(String command ,String javaPid) throws Exception {
        VirtualMachineDescriptor virtualMachineDescriptor = null;
        for (VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
            String pid = descriptor.id();
            if (pid.equals(javaPid)) {
                virtualMachineDescriptor = descriptor;
            }
        }
        HotSpotVirtualMachine virtualMachine = null;
        try {
            if (null == virtualMachineDescriptor) { // 使用 attach(String pid) 这种方式
                virtualMachine = (HotSpotVirtualMachine) VirtualMachine.attach("" + javaPid);
            } else {
                virtualMachine = (HotSpotVirtualMachine) VirtualMachine.attach(virtualMachineDescriptor);
            }
            InputStream inputStream = null;
            if("live".equals(command)){
                inputStream = virtualMachine.heapHisto("-"+ command);
            }
            return  IOUtils.streamTOstr(inputStream);

        } finally {
            if (null != virtualMachine) {
                virtualMachine.detach();
            }
        }
    }
}
